// @flow
import React from 'react'
import { Badge, Tabs, Table, message, Icon, Spin } from 'antd'
import WarningModel from 'components/WarningModel'
import LinkToDeviceOverView from './LinkToDeviceOverView'
import LinkToCustomerOverView from './LinkToCustomerOverView'
import moment from 'moment'
import styles from './Notify.css'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
import { connect } from 'react-redux'
const TabPane = Tabs.TabPane
import R from 'ramda'
import Pagination from './Pagination'

type Props = {
  history: Object,
  data: Object,
  homeHistory: Object,
  userId: string
}

function callback (key) {
  // console.log(key)
}

const flag = false
const size = 'small'

type States = {
  realList: Array<Object>,
  faultList: Array<Object>,
  realCount: number,
  faultCount: number,
  count: number,
  loading: boolean,
  columns: Array<Object>,
  visible: boolean,
  current: number,
  pageSize: number,
  total1: number,
  total2: number,
  realLoading: boolean,
  faultLoading: boolean
}

class Notify extends React.Component {
  state: States
  props: Props
  ignoreMeg: Function
  order: Function
  gotoDetail: Function
  togglePop: Function
  constructor (props: Object) {
    super(props)
    const component = this
    this.state = {
      visible: false,
      realList:[],
      faultList:[],
      realCount: 0,
      faultCount: 0,
      count: 0,
      loading: false,
      columns:  [
        {
          title: '客户',
          dataIndex: 'deviceNo',
          key: 'deviceNo',
          width: 80,
          render: (text, record, index) => {
            return <LinkToCustomerOverView data={record} />
          }
        }, {
          title: '设备',
          dataIndex: 'device',
          key: 'device',
          width: 80,
          render: (text, record, index) => {
            return <LinkToDeviceOverView data={record} />
          }
        }, {
          title: '消息',
          dataIndex: 'message',
          key: 'message',
          width: 100,
          render: text => <font color='red'>{text}</font>
        }, {
          title: '时间',
          dataIndex: 'waringTime',
          key: 'waringTime',
          width: 100,
          render: text => moment.utc(text, 'YYYY-MM-DDTHH:mm:ss.SSSZ').format('YYYY-MM-DD HH:mm:ss')
        }, {
          title: '操作',
          dataIndex: 'x',
          key: 'x',
          width: 50,
          render: (text, record, index) =>
            <WarningModel
              {...{
                ignoreMeg: component.ignoreMeg.bind(this),
                order: component.order.bind(this),
                data: record,
                gotoDetail: component.gotoDetail.bind(this),
                state: this.state,
                index: index
              }} />
        }
      ],
      current: 1,
      pageSize: 5,
      total1: 0,
      total2: 0,
      realLoading: false,
      faultLoading: false
    }
    this.gotoDetail = this.gotoDetail.bind(this)
    this.togglePop = this.togglePop.bind(this)
  }
  componentWillReceiveProps (nextProps) {
    if (!R.equals(nextProps, this.props)) {
      const { userId } = nextProps
      this.getUserName(userId)
    }
  }

  togglePop () {
    this.setState({
      visible: !this.state.visible
    })
  }

  gotoDetail () {
    this.props.homeHistory.history.push('/device-file/3/condition')
  }

  getWarningReal (current, pageSize, loginName) {
    this.setState({
      realLoading: true
    })
    universalFetch(`${__SERVICE_API__}analysis/warings?pageNum=${current}&pageSize=${pageSize}&type=real&status=mq&owner=${loginName}`)
      .then((res) => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          realLoading: false,
          realList:json.result.map((data, index) => {
            data['key'] = index
            return data
          }),
          total1: json.pageInfo.total,
          loading: false,
          realCount: json.pageInfo.total
        })
        const count = this.state.count
        const count1 = count + this.state.realCount
        this.setState({
          count: count1
        })
      })
      .catch((error) => {
        this.setState({
          realLoading: false
        })
        handleFetchError(error)
        console.error(error)
      })
  }

  getWarningFault (current, pageSize, loginName) {
    this.setState({
      faultLoading: true
    })
    universalFetch(`${__SERVICE_API__}analysis/warings?pageNum=${current}&pageSize=${pageSize}&type=fault&status=mq&owner=${loginName}`)
      .then((res) => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          faultLoading: false,
          faultList:json.result.map((data, index) => {
            data['key'] = index
            return data
          }),
          total2: json.pageInfo.total,
          loading: false,
          faultCount: json.pageInfo.total,
          count: json.pageInfo.total
        })
      })
      .catch((error) => {
        this.setState({
          faultLoading: false
        })
        handleFetchError(error)
        console.error(error)
      })
  }
  order (data, index) {
    const _this = this
    universalFetch(`${__SERVICE_API__}analysis/warings/` + data.id + '?type=order',
      {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json;charset=utf-8'
        }
      })
      .then((res) => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        // 删除1行
        if (data.type === 'fault') {
          const dataSource = [..._this.state.faultList]
          dataSource.splice(index, 1)
          // 个数减一
          const count = _this.state.count
          const count1 = count - 1
          _this.setState({
            faultList:dataSource,
            count: count1
          })
        } else {
          const dataSource = [..._this.state.realList]
          dataSource.splice(index, 1)
          // 个数减一
          const count = _this.state.count
          const count1 = count - 1
          _this.setState({
            realList:dataSource,
            count: count1
          })
        }
        message.success('工单生成成功')
      })
      .catch((error) => {
        message.error('工单生成失败')
        handleFetchError(error)
        console.error(error)
      })
  }

  ignoreMeg (data, index) {
    const _this = this
    const values = {
      'type': 'ignore'
    }
    universalFetch(`${__SERVICE_API__}analysis/warings/` + data.id,
      {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/jsoncharset=utf-8'
        },
        body: JSON.stringify(values)
      })
      .then((res) => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        // 删除1行
        if (data.type === 'fault') {
          const dataSource = [..._this.state.faultList]
          dataSource.splice(index, 1)
          // 个数减一
          const count = _this.state.count
          const count1 = count - 1
          _this.setState({
            faultList:dataSource,
            count: count1
          })
        } else {
          const dataSource = [..._this.state.realList]
          dataSource.splice(index, 1)
          // 个数减一
          const count = _this.state.count
          const count1 = count - 1
          _this.setState({
            realList:dataSource,
            count: count1
          })
        }
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }

  getUserName (userId) {
    // universalFetch(`${__SERVICE_API__}sys/users/${userId}`)
    //   .then(res => res.json())
    //   .then((json) => {
    //     const { loginName } = json.result
    //     if (loginName) {
    //       this.getWarningFault(loginName)
    //       this.getWarningReal(loginName)
    //     }
    //   })
    //   .catch((error) => {
    //     handleFetchError(error)
    //     console.error(error)
    //   })
    const { current, pageSize } = this.state
    this.getWarningFault(current, pageSize, userId)
    this.getWarningReal(current, pageSize, userId)
  }
  refreshWarningReal = (current, pageSize) => {
    const { userId } = this.props
    this.getWarningReal(current, pageSize, userId)
  }
  refreshWarningFault = (current, pageSize) => {
    const { userId } = this.props
    this.getWarningFault(current, pageSize, userId)
  }
  render () {
    const { columns, realList, faultList, visible, current, pageSize, total1, total2, realLoading, faultLoading } = this.state
    const count = this.state.count
    const panl = (<Table
      // loading={realLoading}
      columns={columns}
      dataSource={realList}
      pagination={false}
      // pagination={{ pageSize: 5 }}
      showHeader={flag}
      size={size}
      />)

    const panl1 = (<Table
      // loading={faultLoading}
      columns={columns}
      dataSource={faultList}
      pagination={false}
      // pagination={{ pageSize: 5 }}
      showHeader={flag}
      size={size}
      />)

    const content = (<Tabs defaultActiveKey='1' onChange={callback}>
      <TabPane tab='实时告警' key='1'>
        <Spin spinning={realLoading}>
          {panl}
          <Pagination current={current} pageSize={pageSize} total={total1} onChange={this.refreshWarningReal} />
        </Spin>
      </TabPane>
      <TabPane tab='模型预警' key='2'>
        <Spin spinning={faultLoading}>
          {panl1}
          <Pagination current={current} pageSize={pageSize} total={total2} onChange={this.refreshWarningFault} />
        </Spin>
      </TabPane>
    </Tabs>
    )
    return (
      <div className={styles['bell']}>
        <i className='fa fa-bell'
          aria-hidden='true'
          style={{ position: 'relative', cursor: 'pointer' }}
          onClick={this.togglePop}>
          <Badge count={count} style={{
            backgroundColor: '#00d2ff',
            color: '#555',
            boxShadow: '0px 1px 1px 0px rgba(0, 0, 0, .6)',
            fontSize: '12px',
            height: '14px',
            minWidth: '14px',
            padding: '0 4px',
            lineHeight: '14px',
            position: 'absolute',
            top: '-16px',
            left: '-8px',
            cursor: 'pointer'
          }} />
        </i>
        {
          visible ? <div className={styles['bellPop']}>
            <Icon type='caret-up' className={styles['bellIcon']} />
            {content}
          </div> : ''
        }
      </div>
    )
  }
}

const mapStateToProps = state => {
  return {
    homeHistory: state.homeHistory,
    userId: state.user.userId
  }
}
export default connect(mapStateToProps, {})(Notify)
